package com.ruoyi.prod.service.impl;

import java.util.HashMap;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.prod.es.EsProd;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.index.Settings;
import org.springframework.data.elasticsearch.core.query.HighlightQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Map;

import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.prod.domain.TbProdInfo;
import com.ruoyi.prod.mapper.TbProdMapper;
import com.ruoyi.prod.domain.TbProd;
import com.ruoyi.prod.service.ITbProdService;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 商品管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-02
 */
@Service
@Slf4j
public class TbProdServiceImpl implements ITbProdService 
{
    @Autowired
    private TbProdMapper tbProdMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 查询商品管理
     * 
     * @param prodId 商品管理主键
     * @return 商品管理
     */
    @Override
    public TbProd selectTbProdByProdId(Integer prodId)
    {
        return tbProdMapper.selectTbProdByProdId(prodId);
    }

    /**
     * 查询商品管理列表
     * 
     * @param tbProd 商品管理
     * @return 商品管理
     */
    @Override
    public List<TbProd> selectTbProdList(TbProd tbProd)
    {
        return tbProdMapper.selectTbProdList(tbProd);
    }

    /**
     * 新增商品管理
     * 
     * @param tbProd 商品管理
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTbProd(TbProd tbProd)
    {

//        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(TbProd.class);
//        boolean exists = indexOps.exists();
//        if(!exists){
//            indexOps.create();
//            Document mapping = indexOps.createMapping();
//            indexOps.putMapping(mapping);
//        }
//        elasticsearchRestTemplate.save(tbProd);
        tbProd.setCreateTime(DateUtils.getNowDate());
        int rows = tbProdMapper.insertTbProd(tbProd);
        insertTbProdInfo(tbProd);
        return rows;
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void sycnProdList(){
        log.info("开始执行同步商品数据");
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsProd.class);
        boolean exists = indexOps.exists();
        if(!exists){
            indexOps.create();
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }
        List<TbProd> tbProds = tbProdMapper.selectTbProdList(null);
        for (TbProd tbProd : tbProds) {
            EsProd esProd = BeanUtil.toBean(tbProd, EsProd.class);
            elasticsearchRestTemplate.save(esProd);
        }

        log.info("执行同步商品数据结束");

    }

    /**
     * 修改商品管理
     * 
     * @param tbProd 商品管理
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTbProd(TbProd tbProd)
    {
        tbProd.setUpdateTime(DateUtils.getNowDate());
        tbProdMapper.deleteTbProdInfoByProdId(tbProd.getProdId());
        insertTbProdInfo(tbProd);
        return tbProdMapper.updateTbProd(tbProd);
    }

    /**
     * 批量删除商品管理
     * 
     * @param prodIds 需要删除的商品管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTbProdByProdIds(Integer[] prodIds)
    {
        tbProdMapper.deleteTbProdInfoByProdIds(prodIds);
        return tbProdMapper.deleteTbProdByProdIds(prodIds);
    }

    /**
     * 删除商品管理信息
     * 
     * @param prodId 商品管理主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTbProdByProdId(Integer prodId)
    {
        tbProdMapper.deleteTbProdInfoByProdId(prodId);
        return tbProdMapper.deleteTbProdByProdId(prodId);
    }

    @Override
    public TableDataInfo getListPage(TbProd tbProd, String pageNum1, String pageSize1) {
        log.info("开始Es查询");
        Integer pageNum = Integer.valueOf(pageNum1);
        Integer pageSize = Integer.valueOf(pageSize1);
        Integer from=0;
        if(pageNum>0){
            from=pageNum-1;
        }
        PageRequest page = PageRequest.of(from, pageSize);
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if(StringUtils.isNotEmpty(tbProd.getProdName())){
            queryBuilder.must(QueryBuilders.matchQuery("prodName",tbProd.getProdName()));
            queryBuilder.must(QueryBuilders.matchQuery("prodSpu",tbProd.getProdSpu()));
        }
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder prodName = highlightBuilder.field("prodName").preTags("<font color='red'>").postTags("</font>");
        HighlightBuilder prodSpu = highlightBuilder.field("prodSpu").preTags("<font color='red'>").postTags("</font>");
        FieldSortBuilder prodId = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(queryBuilder).withPageable(page).withSorts(prodId).withHighlightBuilder(prodName).withHighlightBuilder(prodSpu);

        SearchHits<EsProd> search = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), EsProd.class);
        ArrayList<EsProd> list = new ArrayList<>();
        for (SearchHit<EsProd> searchHit : search.getSearchHits()) {
            EsProd content = searchHit.getContent();
            List<String> prodName1 = searchHit.getHighlightField("prodName");
            if(prodName1.size()>0){
                for (String s : prodName1) {
                    content.setProdName(s);
                }
            }

            List<String> prodSpu1 = searchHit.getHighlightField("prodSpu");
            if(prodSpu1.size()>0){
                for (String s : prodSpu1) {
                    content.setProdSpu(s);
                }
            }

            list.add(content);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(search.getTotalHits());
        log.info("Es查询结束");
        return rspData;
    }

    /**
     * 新增商品信息信息
     * 
     * @param tbProd 商品管理对象
     */
    public void insertTbProdInfo(TbProd tbProd)
    {
        List<TbProdInfo> tbProdInfoList = tbProd.getTbProdInfoList();
        Integer prodId = tbProd.getProdId();
        if (StringUtils.isNotNull(tbProdInfoList))
        {
            List<TbProdInfo> list = new ArrayList<TbProdInfo>();
            for (TbProdInfo tbProdInfo : tbProdInfoList)
            {
                tbProdInfo.setProdId(prodId);
                list.add(tbProdInfo);
            }
            if (list.size() > 0)
            {
                tbProdMapper.batchTbProdInfo(list);
            }
        }
    }
}
